<template>
  <div>
    <qrcode-stream
        class="qrcode-wrap"
        :torch="torch"
        v-memo="[torch]"
        :constraints="selectedConstraints"
        @error="onError"
        @detect="onDetect"
    >
<!--    @camera-on="onCameraReady"-->
<!--      @stop="stopCamera"-->
    <!-- 闪光灯开关 -->
    <div class="torch-wrap">
      <div class="torch" @click="() => (torch = !torch)">
        {{ torch ? "关闭闪光灯" : "打开闪光灯" }}
      </div>
    </div>
    </qrcode-stream>
  </div>
</template>

<script setup lang="ts">
import { ref } from "vue";
import { useRouter } from 'vue-router';
import { QrcodeStream } from "vue-qrcode-reader"; // 引入扫码库

// const emit = defineEmits(["on-success"]); // 父组件事件
const error = ref("");
const torch = ref(false);
const isSupportTorch = ref(false); // 是否支持闪光灯
const selectedConstraints = ref({ facingMode: "environment" }); // 摄像头设置
const router = useRouter(); // 获取 Vue Router 实例
sessionStorage.setItem("qr-data", "")
// 错误处理
function onError(err: any) {
  error.value = `[${err.name}]: ${err.message}`;
  alert(error.value);
}

// 扫描结果
function onDetect(detectedCodes: any) {
  if (detectedCodes.length > 0) {
    onDecode(detectedCodes[0]?.rawValue);
  }
}

// 解码结果，发送给父组件
function onDecode(text: string) {
  // emit("on-success", text);
  stopCamera(); // 停止摄像头
  //alert(text)
  sessionStorage.setItem("qr-data", text)
  router.back()
}

// 摄像头准备好
function onCameraReady(capabilities: any) {
  isSupportTorch.value = !!capabilities.torch;
}

// 停止摄像头
function stopCamera() {
  const videoElement = document.querySelector("video");
  if (videoElement) {
    const stream = videoElement.srcObject as MediaStream;
    const tracks = stream?.getTracks();
    tracks?.forEach((track) => track.stop()); // 停止所有视频流
  }
}
</script>

<style scoped>
.qrcode-wrap {
  position: fixed !important;
  top: 0;
  right: 0;
  bottom: 0;
  left: 0;
  width: 100vw;
  height: 100vh;
  z-index: 1 !important;
  //background: rgba(0, 0, 0, 0.5);
}
.torch-wrap {
  width: 18.75rem;
  height: 12.5rem;
  position: fixed !important;
  left: 50%;
  top: 50%;
  transform: translate(-50%, -30%);
  z-index: 20;
}
.torch {
  position: fixed;
  bottom: -6.25rem;
  left: 50%;
  transform: translateX(-50%);
  z-index: 20;
  color: #fff;
  display: flex;
  flex-direction: column;
  align-items: center;
}
</style>
